﻿using System;
using System.Xml;
using System.Xml.XPath;

using Our.Umbraco.UniversalMediaPicker.Providers.TwitPic.Model;
using TheOutfield.UmbExt.UniversalMediaPicker.Xslt;

namespace Our.Umbraco.UniversalMediaPicker.Providers.TwitPic
{
	public class TwitPicXsltExtension : AbstractXsltExtension
	{
	
		//// GetMedia - to return the XML for the TwitPic!
	
		/// <summary>
		/// Gets the HTML for the TwitPic.
		/// </summary>
		/// <param name="twitPicId">The TwitPic Id.</param>
		/// <returns></returns>
		public static string GetHtml(string twitPicId)
		{
			var twitPic = new TwitPicImage()
			{
				ShortId = twitPicId,
				Message = "TwitPic"
			};
			return twitPic.ToString();
		}

		/// <summary>
		/// Gets the HTML for the TwitPic.
		/// </summary>
		/// <param name="dtdid">The DataType Id.</param>
		/// <param name="twitPicId">The TwitPic Id.</param>
		/// <returns></returns>
		public static string GetHtml(int dtdid, string twitPicId)
		{
			var provider = GetProvider<TwitPicProvider>(dtdid);
			if (provider!= null)
			{
				var image = provider.Service.GetImage(twitPicId);
				if (image != null)
				{
					return image.ToString();
				}
			}

			return GetHtml(twitPicId);
		}

		public static XPathNodeIterator GetUser(int dtdid)
		{
			return GetUser(dtdid, null);
		}

		public static XPathNodeIterator GetUser(int dtdid, string username)
		{
			var provider = GetProvider<TwitPicProvider>(dtdid);
			if (provider != null)
			{
				return GetUser(provider, username);
			}
			
			return null;
		}

		private static XPathNodeIterator GetUser(TwitPicProvider provider, string username)
		{
			if (provider != null)
			{
				var reader = provider.Service.GetUserXml(username);
				if (reader != null)
				{
					return reader.ToXPathNavigator().Select("/");
				}
			}

			return null;
		}

		public static string GetUsername(int dtdid)
		{
			var provider = GetProvider<TwitPicProvider>(dtdid);
			if (provider != null)
			{
				return provider.Service.GetUsername();
			}

			return string.Empty;
		}
	}
}
